import { contextBridge, ipcRenderer } from 'electron'
import { ElectronAPI, FileInfo } from '../src/types/electron'

// Define the API implementation
const electronAPI: ElectronAPI = {
  // AI 功能
  invokeAI: (action: string, text: string, options?: any) =>
    ipcRenderer.invoke('ai:invoke', { action, text, options }),

  streamAI: (action: string, text: string, options?: any, requestId?: string) =>
    ipcRenderer.invoke('ai:stream', { action, text, options, requestId }),

  testAIConnection: () =>
    ipcRenderer.invoke('ai:test-connection'),

  // AI 配置管理
  getAIConfig: () =>
    ipcRenderer.invoke('ai:get-config'),

  updateAIConfig: (config: any) =>
    ipcRenderer.invoke('ai:update-config', config),

  getAvailableModels: () =>
    ipcRenderer.invoke('ai:get-available-models'),

  getSupportedProviders: () =>
    ipcRenderer.invoke('ai:get-supported-providers'),

  validateAIConfig: (config: any) =>
    ipcRenderer.invoke('ai:validate-config', config),

  healthCheck: () =>
    ipcRenderer.invoke('ai:health-check'),

  // 高级 AI 聊天功能
  chatWithAI: (params: { messages: Array<{ role: string; content: string }>; options?: any }) =>
    ipcRenderer.invoke('ai:chat', params),

  streamChatWithAI: (params: { messages: Array<{ role: string; content: string }>; options?: any; requestId?: string }) => 
      ipcRenderer.invoke('ai:stream-chat', params),

  // 文件操作
  openFile: (filePath?: string) =>
    ipcRenderer.invoke('file:open', filePath),

  saveFile: (content: string, filePath?: string) =>
    ipcRenderer.invoke('file:save', content, filePath),

  saveFileAs: (content: string) =>
    ipcRenderer.invoke('file:save-as', content),

  getRecentFiles: (): Promise<FileInfo[]> =>
    ipcRenderer.invoke('file:get-recent'),

  showOpenDialog: () =>
    ipcRenderer.invoke('dialog:show-open'),

  showSaveDialog: () =>
    ipcRenderer.invoke('dialog:show-save'),

  showInputDialog: (options: { title: string; default?: string }) =>
    ipcRenderer.invoke('dialog:show-input', options),

  // 图片上传
  handleImageUpload: (data: { imageData: string; fileName: string; docPath: string }) =>
    ipcRenderer.invoke('file:handle-image-upload', data),

  // 设置管理
  getSettings: () =>
    ipcRenderer.invoke('settings:get'),

  updateSettings: (settings: any) =>
    ipcRenderer.invoke('settings:update', settings),

  // 应用信息
  getAppVersion: () =>
    ipcRenderer.invoke('app:get-version'),

  // 主题切换
  setTheme: (theme: 'light' | 'dark' | 'auto') =>
    ipcRenderer.invoke('theme:set', theme),

  getTheme: () =>
    ipcRenderer.invoke('theme:get'),

  // 事件监听 - AI 流式响应
  onAIStreamChunk: (callback: (data: { requestId?: string; chunk: string; action: string }) => void) => {
    const subscription = (_event: any, data: { requestId?: string; chunk: string; action: string }) => callback(data)
    ipcRenderer.on('ai:stream-chunk', subscription)

    return () => {
      ipcRenderer.removeListener('ai:stream-chunk', subscription)
    }
  },

  onAIStreamEnd: (callback: (data: { requestId?: string; action: string; result?: string }) => void) => {
    const subscription = (_event: any, data: { requestId?: string; action: string; result?: string }) => callback(data)
    ipcRenderer.on('ai:stream-end', subscription)

    return () => {
      ipcRenderer.removeListener('ai:stream-end', subscription)
    }
  },

  onAIStreamError: (callback: (data: { requestId?: string; error: string; action: string }) => void) => {
    const subscription = (_event: any, data: { requestId?: string; error: string; action: string }) => callback(data)
    ipcRenderer.on('ai:stream-error', subscription)

    return () => {
      ipcRenderer.removeListener('ai:stream-error', subscription)
    }
  },

  // AI 聊天流式响应
  onAIChatChunk: (callback: (data: { requestId?: string; chunk: string }) => void) => {
    const subscription = (_event: any, data: { requestId?: string; chunk: string }) => callback(data)
    ipcRenderer.on('ai:chat-chunk', subscription)

    return () => {
      ipcRenderer.removeListener('ai:chat-chunk', subscription)
    }
  },

  onAIChatEnd: (callback: (data: { requestId?: string; result?: string }) => void) => {
    const subscription = (_event: any, data: { requestId?: string; result?: string }) => callback(data)
    ipcRenderer.on('ai:chat-end', subscription)

    return () => {
      ipcRenderer.removeListener('ai:chat-end', subscription)
    }
  },

  onAIChatError: (callback: (data: { requestId?: string; error: string }) => void) => {
    const subscription = (_event: any, data: { requestId?: string; error: string }) => callback(data)
    ipcRenderer.on('ai:chat-error', subscription)

    return () => {
      ipcRenderer.removeListener('ai:chat-error', subscription)
    }
  },

  onFileChanged: (callback: (path: string, content: string) => void) => {
    const subscription = (_event: any, path: string, content: string) => callback(path, content)
    ipcRenderer.on('file:changed', subscription)

    return () => {
      ipcRenderer.removeListener('file:changed', subscription)
    }
  },

  onThemeChanged: (callback: (theme: string) => void) => {
    const subscription = (_event: any, theme: string) => callback(theme)
    ipcRenderer.on('theme:changed', subscription)

    return () => {
      ipcRenderer.removeListener('theme:changed', subscription)
    }
  },

  // 快捷键
  registerShortcut: (shortcut: string, action: string) =>
    ipcRenderer.invoke('shortcut:register', shortcut, action),

  unregisterShortcut: (shortcut: string) =>
    ipcRenderer.invoke('shortcut:unregister', shortcut),

  // 窗口控制
  minimizeWindow: () =>
    ipcRenderer.invoke('window:minimize'),

  maximizeWindow: () =>
    ipcRenderer.invoke('window:maximize'),

  closeWindow: () =>
    ipcRenderer.invoke('window:close'),

  // 开发者工具 (仅在开发环境)
  openDevTools: () =>
    ipcRenderer.invoke('dev:open-tools'),

  // 全局快捷键
  onGlobalShortcut: (callback: (shortcut: string) => void) => {
    const subscription = (_event: any, shortcut: string) => callback(shortcut)
    ipcRenderer.on('global:shortcut', subscription)

    return () => {
      ipcRenderer.removeListener('global:shortcut', subscription)
    }
  },

  // Git功能
  initGitRepository: (filePath: string) =>
    ipcRenderer.invoke('git:initRepository', filePath),

  isFileInGitRepository: (filePath: string) =>
    ipcRenderer.invoke('git:isFileInRepository', filePath),

  addFileToGit: (filePath: string, message?: string) =>
    ipcRenderer.invoke('git:addFile', filePath, message),

  getFileGitHistory: (filePath: string) =>
    ipcRenderer.invoke('git:getFileHistory', filePath),

  getFileContentAtCommit: (filePath: string, commitHash: string) =>
    ipcRenderer.invoke('git:getFileContentAtCommit', filePath, commitHash),

  getFileGitDiff: (filePath: string, commitHash1: string, commitHash2: string) =>
    ipcRenderer.invoke('git:getFileDiff', filePath, commitHash1, commitHash2),

  hasUncommittedChanges: (filePath: string) =>
    ipcRenderer.invoke('git:hasUncommittedChanges', filePath),

  commitGitChanges: (filePath: string, message: string) =>
    ipcRenderer.invoke('git:commitChanges', filePath, message)
}

// Expose the API to the renderer process
contextBridge.exposeInMainWorld('electronAPI', electronAPI)